{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Credits: https://github.com/bansalkanav/Machine_Learning_and_Deep_Learning"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Regular Expressions\n",
    "\n",
    "**What are Regualar Expressions?**  \n",
    "A regular expression, often abbreviated as \"regex\" or \"regexp,\" is a powerful tool used in computer science and text processing to describe and match patterns in strings. It's a sequence of characters that defines a search pattern. These patterns can be used for tasks like searching, extracting, replacing, and validating text.\n",
    "\n",
    "Regular expressions are widely used in tasks like text searching and manipulation, data validation, parsing, and more. They are supported by many programming languages and text processing tools, making them a versatile and essential tool for working with text data.\n",
    "\n",
    "**Why Regular Expressions?**  \n",
    "Regular expressions are used for a variety of tasks in computer science, data processing, and text analysis due to their powerful pattern matching capabilities. Here are some key reasons why regular expressions are widely used:\n",
    "\n",
    "1. **Pattern Matching:** Regular expressions allow you to search for specific patterns or sequences of characters within a larger body of text. This is useful for tasks like finding specific words, dates, email addresses, or other structured information.\n",
    "\n",
    "2. **Text Extraction:** They can be used to extract specific pieces of information from a text document, such as names, phone numbers, URLs, or any other structured data.\n",
    "\n",
    "3. **Data Validation:** Regular expressions are used to validate input data. For example, you can use them to check if a user-provided email address or phone number is in the correct format.\n",
    "\n",
    "4. **Search and Replace:** They enable you to search for specific patterns in a text and replace them with something else. This is useful for tasks like cleaning up data or making text substitutions.\n",
    "\n",
    "5. **Parsing and Tokenization:** Regular expressions are essential for breaking down text into smaller units or tokens. This is used in tasks like natural language processing and compiler design.\n",
    "\n",
    "6. **Web Scraping:** When extracting data from websites, regular expressions can be used to locate and extract specific elements or information from HTML pages.\n",
    "\n",
    "7. **Log File Analysis:** Regular expressions are invaluable for searching and parsing log files, allowing you to extract important information or identify patterns of interest.\n",
    "\n",
    "8. **Pattern Validation:** They are used to validate whether a string adheres to a specific pattern or format, such as checking if a password meets certain criteria.\n",
    "\n",
    "9. **Data Transformation and Cleaning:** Regular expressions can be used to clean and transform text data. For example, removing unnecessary characters or formatting.\n",
    "\n",
    "10. **Language Agnostic:** Regular expressions are supported by most programming languages, making them a versatile tool that can be applied in a wide range of contexts.\n",
    "\n",
    "11. **Efficiency:** When used correctly, regular expressions can provide very efficient search and match operations, especially for complex patterns.\n",
    "\n",
    "Overall, regular expressions are a fundamental tool for working with text data and are an essential skill for tasks ranging from data preprocessing to text analysis and beyond. They provide a flexible and powerful means to perform complex pattern matching operations.\n",
    "\n",
    "\n",
    "**Applications of Regular Expressions**  \n",
    "Regular expressions (regex) find applications in a wide range of real-time scenarios across various domains. Here are some of the most important applications of regex:\n",
    "\n",
    "1. **Data Validation and Form Input:**\n",
    "   - Ensuring that user-provided data (like email addresses, phone numbers, passwords, etc.) adhere to specified formats before processing.\n",
    "\n",
    "2. **Search and Replace in Text Editors:**\n",
    "   - Find and replace operations in text editors or IDEs, allowing for quick and precise changes in code or documents.\n",
    "\n",
    "3. **Log File Parsing and Analysis:**\n",
    "   - Extracting relevant information from log files, helping to identify patterns, errors, or anomalies in system logs.\n",
    "\n",
    "4. **Web Scraping and Data Extraction:**\n",
    "   - Extracting specific information from web pages, like email addresses, phone numbers, product names, etc., for further analysis.\n",
    "\n",
    "5. **Data Cleaning and Transformation:**\n",
    "   - Preprocessing text data by removing unnecessary characters, fixing formatting issues, and standardizing data for analysis.\n",
    "\n",
    "6. **Search Engines and Information Retrieval:**\n",
    "   - Powering search engines for matching user queries to relevant content on websites or databases.\n",
    "\n",
    "7. **URL Routing and Validation:**\n",
    "   - Validating and parsing URLs to ensure they follow the correct format and extracting specific parameters from them.\n",
    "\n",
    "8. **Lexical Analysis in Compiler Design:**\n",
    "   - Tokenizing source code into meaningful units for further processing by a compiler.\n",
    "\n",
    "9. **Natural Language Processing (NLP):**\n",
    "   - Tokenizing sentences or words, extracting entities (like names, dates, locations), and performing advanced text processing tasks.\n",
    "\n",
    "10. **Network Security and Firewall Rules:**\n",
    "    - Defining and enforcing rules for allowing or blocking specific types of traffic based on patterns in network traffic logs.\n",
    "\n",
    "11. **Database Querying and Validation:**\n",
    "    - Validating and querying databases for specific patterns or formats, such as social security numbers, credit card numbers, etc.\n",
    "\n",
    "12. **Formal Language Theory and Automata:**\n",
    "    - In computer science theory, regex is used in the definition of regular languages and finite automata.\n",
    "\n",
    "13. **Validation of Configuration Files:**\n",
    "    - Ensuring that configuration files for software or systems follow the correct syntax and structure.\n",
    "\n",
    "14. **Extracting Metadata from Documents:**\n",
    "    - Parsing documents (like PDFs, Word documents) to extract metadata such as titles, authors, dates, etc.\n",
    "\n",
    "15. **URL Rewriting in Web Servers:**\n",
    "    - Modifying URLs on the fly to improve SEO or to direct traffic to specific pages.\n",
    "\n",
    "16. **Pattern Matching in DNA Sequences:**\n",
    "    - Identifying specific genetic sequences or motifs in DNA for biological research.\n",
    "\n",
    "These are just some of the many real-time applications of regular expressions. Their versatility and powerful pattern-matching capabilities make them an invaluable tool in various fields of computer science and data processing."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**References for Practice**  \n",
    "Try to solve all the interactive tutorial from below mentioned website:\n",
    "\n",
    "https://regexone.com/lesson/introduction_abcs\n",
    "\n",
    "https://regex101.com"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Meta Characters\n",
    "`.`, `^`, `$`, `*`, `+`, `?`, `{`, `}`, `[`, `]`, `(`, `)`, `|`, `\\`\n",
    "\n",
    "## User-defined Character Classes\n",
    "- `[abc]` - Match either a or b or c\n",
    "- `[^abc]` - Match any character except a or b or c\n",
    "- `[a-z]` - Match a lower case english alphabet character\n",
    "- `[A-Z]` - Match an upper case english alphabet character\n",
    "- `[a-zA-Z]` - Match any english alphabet character\n",
    "- `[0-9]` - Match any digit character\n",
    "- `[a-zA-Z0-9_]` - Match any alphanumeric character\n",
    "- `[^a-zA-Z0-9_]` - Match any character except alphanumeric character\n",
    "\n",
    "## Pre-defined Character Classes\n",
    "- `\\d` - Match a digit character i.e. `[0-9]`\n",
    "- `\\D` - Match any character except digit character. i.e. `[^0-9]`\n",
    "- `\\w` - Match an alpha-numeric character i.e. `[a-zA-Z0-9_]`\n",
    "- `\\W` - Match any character except alpha-numeric character i.e. `[^a-zA-Z0-9_]`\n",
    "- `\\s` - Match a space character.\n",
    "- `\\S` - Match any character except space.\n",
    "- `\\t` - Match a tab character.\n",
    "- `\\n` - Match a next line character.\n",
    "\n",
    "## Quantifiers\n",
    "- `a*` - Match zero or more number of characters\n",
    "- `a+` - Match one or more number of characters\n",
    "- `a?` - Match atmost 1 character i.e. 0 or 1\n",
    "- `a{n}` - Match exactly n number of character\n",
    "- `a{m, n}` - Match atleast m number and atmost n number of characters\n",
    "\n",
    "## Groups\n",
    "- Capturing Groups - `(X)`\n",
    "- Non Capturing Groups - `(?:X)`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Importing the Required Module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.fullmatch()\n",
    "\n",
    "It returns a match object if and only if the entire string matches the pattern. Otherwise, it will return `None`.\n",
    "\n",
    "**Syntax**  \n",
    "```python\n",
    "import re\n",
    "re.findall(<regex_pattern>, string)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Regular Expression to match an Indian Phone number\n",
    "\n",
    "**Rules:**  \n",
    "1. Should start with either 6 or 7 or 8 or 9\n",
    "2. Should contain exactly 10 digits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Enter a mobile number to validate:  9090909090\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9090909090 is valid.\n"
     ]
    }
   ],
   "source": [
    "# Step 1 - Ask the user to enter a phone number\n",
    "user_entered_mobile_number = input(\"Enter a mobile number to validate: \")\n",
    "\n",
    "# Step 2 - Create a regex pattern for Indian Phone Numbers\n",
    "regex = r\"[6-9]\\d{9}\"\n",
    "\n",
    "# Step 3 - Match the Regex with the user entered mobile number\n",
    "match = re.fullmatch(regex, user_entered_mobile_number)\n",
    "\n",
    "# Step 4 - If match exist, print \"Valid\"\n",
    "if match:\n",
    "    print(user_entered_mobile_number, 'is valid.')\n",
    "else:\n",
    "    print(user_entered_mobile_number, 'not valid.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preceding `r` in a string \n",
    "\n",
    "The 'r' at the start of the pattern string designates a python \"raw\" string.  \n",
    "The 'r' means that the string is to be treated as a raw string, which means all escape codes will be ignored.  \n",
    "For an example:  \n",
    "`'\\n'` will be treated as a newline character, while `r'\\n'` will be treated as the characters \\ followed by n."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is the first line. \n",
      "\n",
      "There are two new lines before this line.\n"
     ]
    }
   ],
   "source": [
    "print('This is the first line. \\n')\n",
    "print('There are two new lines before this line.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is the first line. \\n\n",
      "There are two new lines before this line.\n"
     ]
    }
   ],
   "source": [
    "print(r'This is the first line. \\n')\n",
    "print(r'There are two new lines before this line.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Regular Expression to validate a Python Identifier\n",
    "\n",
    "**Rules:**  \n",
    "1. Should contain only alpha-numeric character (i.e. No special characters allowed)\n",
    "2. Should never start with a digit\n",
    "3. Has no length limit\n",
    "4. Reserved words or keywords not allowed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Enter any identifier to validate: var_1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "var_1 is valid.\n"
     ]
    }
   ],
   "source": [
    "# Step 1 - Ask the user to enter a python identifier\n",
    "user_defined_identifier = input(\"Enter any identifier to validate:\")\n",
    "\n",
    "# Step 2 - Create a regex pattern for a valid Python Identifier\n",
    "regex = r\"[a-zA-Z_]\\w*\"\n",
    "\n",
    "# Step 3 - Match the Regex with the user entered identifier\n",
    "match = re.fullmatch(regex, user_defined_identifier)\n",
    "\n",
    "# Step 4 - If match exist, print \"Valid\"\n",
    "if match:\n",
    "    print(user_defined_identifier, 'is valid.')\n",
    "else:\n",
    "    print(user_defined_identifier, 'not valid.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Enter any identifier to validate: if\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You have entered a pre-defined python keyword.\n"
     ]
    }
   ],
   "source": [
    "# Create a list of predefined keywords in Python\n",
    "keywords = ['if', 'for', 'def', 'while', 'True', 'False', \"None\"]\n",
    "\n",
    "# Step 1 - Ask the user to enter a python identifier\n",
    "user_defined_identifier = input(\"Enter any identifier to validate:\")\n",
    "\n",
    "# Step 2 - Create a regex pattern for a valid Python Identifier\n",
    "regex = r\"[a-zA-Z_]\\w*\"\n",
    "\n",
    "# Step 3 - Match the Regex with the user entered identifier\n",
    "match = re.fullmatch(regex, user_defined_identifier)\n",
    "\n",
    "# Step 4 - If match exist, print \"Valid\"\n",
    "if user_defined_identifier in keywords:\n",
    "    print(\"You have entered a pre-defined python keyword.\")\n",
    "elif match:\n",
    "    print(user_defined_identifier, 'is valid.')\n",
    "else:\n",
    "    print(user_defined_identifier, 'not valid.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.findall()\n",
    "\n",
    "It iterates over a string to find a subset of characters that match a specified pattern. It will return a list of every pattern match that occurs in a given string. The string is scanned left-to-right, and matches are returned in the order found.\n",
    "\n",
    "**Syntax**\n",
    "```python\n",
    "import re\n",
    "re.findall(<regex_pattern>, string)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "string = \"\"\"MediaTek MT8183 Processor4 GB LPDDR4 RAMAndroid Operating System29.46 cm (11.6 Inch) Display1 Year Pick and Drop Warranty\n",
    "Intel Core i5 Processor (11th Gen)8 GB DDR4 RAMWindows 11 Operating System512 GB SSD39.62 cm (15.6 Inch) Display1 Year Carry-in Warranty\n",
    "AMD Athlon Dual Core Processor8 GB DDR4 RAMWindows 11 Operating System512 GB SSD39.62 cm (15.6 Inch) Display1 Year Onsite Warranty\n",
    "Apple M2 Processor8 GB Unified Memory RAMMac OS Operating System256 GB SSD34.54 cm (13.6 Inch) DisplayBuilt-in Apps: iMovie, Siri, GarageBand, Pages, Numbers, Photos, Keynote, Safari, Mail, FaceTime, Messages, Maps, Stocks, Home, Voice Memos, Notes, Calendar, Contacts, Reminders, Photo Booth, Preview, Books, App Store, Time Machine, TV, Music, Podcasts, Find My, QuickTime Player1 Year Limited Warranty\n",
    "Intel Core i3 Processor (10th Gen)8 GB LPDDR4X RAM64 bit Windows 11 Operating System512 GB SSD39.62 cm (15.6 inch) Display1 Year Onsite Warranty\n",
    "AMD Athlon Dual Core Processor4 GB DDR4 RAMDOS Operating System256 GB SSD39.62 cm (15.6 Inch) Display1 Year Onsite Warranty\n",
    "Intel Celeron Dual Core Processor (4th Gen)8 GB DDR4 RAM64 bit Windows 11 Operating System256 GB SSD39.62 cm (15.6 inch) Display1 Years\n",
    "MediaTek MT8183 Processor4 GB LPDDR4 RAMAndroid Operating System29.46 cm (11.6 Inch) Display1 Year Pick and Drop Warranty\n",
    "Intel Core i3 Processor (12th Gen)8 GB LPDDR5 RAM64 bit Windows 11 Operating System256 GB SSD39.62 cm (15.6 Inch) Display1 Year International Travelers Warranty\n",
    "AMD Ryzen 5 Hexa Core Processor8 GB DDR4 RAM64 bit Windows 11 Operating System512 GB SSD39.62 cm (15.6 inch) DisplayMicrosoft Office Home 2019 & Office 365, HP Documentation, HP SSRM, HP Smart1 Year Onsite Warranty\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract the Processor Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['MediaTek MT8183 Processor',\n",
       " 'Intel Core i5 Processor',\n",
       " 'AMD Athlon Dual Core Processor',\n",
       " 'Apple M2 Processor',\n",
       " 'Intel Core i3 Processor',\n",
       " 'AMD Athlon Dual Core Processor',\n",
       " 'Intel Celeron Dual Core Processor',\n",
       " 'MediaTek MT8183 Processor',\n",
       " 'Intel Core i3 Processor',\n",
       " 'AMD Ryzen 5 Hexa Core Processor']"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'(?:MediaTek|AMD|Intel|Apple)[\\s\\w]+Processor'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract the RAM Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['4 GB LPDDR4 RAM',\n",
       " '(11th Gen)8 GB DDR4 RAM',\n",
       " '8 GB DDR4 RAM',\n",
       " '8 GB Unified Memory RAM',\n",
       " '(10th Gen)8 GB LPDDR4X RAM',\n",
       " '4 GB DDR4 RAM',\n",
       " '(4th Gen)8 GB DDR4 RAM',\n",
       " '4 GB LPDDR4 RAM',\n",
       " '(12th Gen)8 GB LPDDR5 RAM',\n",
       " '8 GB DDR4 RAM']"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'(?:\\([\\w\\s]+\\))?\\d+\\sGB[\\s\\w]+RAM'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extracting the OS Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Android Operating System',\n",
       " 'Windows 11 Operating System',\n",
       " 'Windows 11 Operating System',\n",
       " 'Mac OS Operating System',\n",
       " '64 bit Windows 11 Operating System',\n",
       " 'DOS Operating System',\n",
       " '64 bit Windows 11 Operating System',\n",
       " 'Android Operating System',\n",
       " '64 bit Windows 11 Operating System',\n",
       " '64 bit Windows 11 Operating System']"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'(?:\\d+\\sbit|Android|Mac|Window|DOS)[\\s\\w]+Operating System'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extracting Storage Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['512 GB SSD',\n",
       " '512 GB SSD',\n",
       " '256 GB SSD',\n",
       " '512 GB SSD',\n",
       " '256 GB SSD',\n",
       " '256 GB SSD',\n",
       " '256 GB SSD',\n",
       " '512 GB SSD']"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'[\\d]+\\s(?:GB|TB)\\s(?:HDD|SSD)'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract Display Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['29.46 cm (11.6 Inch) Display',\n",
       " '39.62 cm (15.6 Inch) Display',\n",
       " '39.62 cm (15.6 Inch) Display',\n",
       " '34.54 cm (13.6 Inch) Display',\n",
       " '39.62 cm (15.6 inch) Display',\n",
       " '39.62 cm (15.6 Inch) Display',\n",
       " '39.62 cm (15.6 inch) Display',\n",
       " '29.46 cm (11.6 Inch) Display',\n",
       " '39.62 cm (15.6 Inch) Display',\n",
       " '39.62 cm (15.6 inch) Display']"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'\\d+\\.?\\d+\\scm.*Display'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract the Warranty Details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1 Year Pick and Drop Warranty',\n",
       " '1 Year Carry-in Warranty',\n",
       " '1 Year Onsite Warranty',\n",
       " '1 Year Limited Warranty',\n",
       " '1 Year Onsite Warranty',\n",
       " '1 Year Onsite Warranty',\n",
       " '1 Year Pick and Drop Warranty',\n",
       " '1 Year International Travelers Warranty',\n",
       " '1 Year Onsite Warranty']"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "regex = r'\\d+\\sYear.*Warranty'\n",
    "\n",
    "re.findall(regex, string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Search and Replace"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T03:09:22.948642Z",
     "start_time": "2018-06-07T03:09:22.941970Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a#b#j#k#h#\n"
     ]
    }
   ],
   "source": [
    "# re.sub(pattern, replacement, targetString)\n",
    "\n",
    "import re\n",
    "\n",
    "s = re.sub('\\d', '#', 'a7b6j9k2h4')\n",
    "\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T03:24:38.470165Z",
     "start_time": "2018-06-07T03:24:38.460338Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Phone num:  1233-123-345 # This is a phone\n",
      "Phone num:  1233-123-345 \n",
      "Phone num:  1233123345\n"
     ]
    }
   ],
   "source": [
    "# re.sub(regex, replacement, targetString)\n",
    "\n",
    "import re\n",
    "\n",
    "phone = '1233-123-345 # This is a phone'\n",
    "\n",
    "print('Phone num: ', phone)\n",
    "\n",
    "num = re.sub('#.*$', '', phone)\n",
    "\n",
    "print('Phone num: ',num)\n",
    "\n",
    "num = re.sub('\\D', '', phone)\n",
    "\n",
    "print('Phone num: ', num)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.split()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T03:12:31.994925Z",
     "start_time": "2018-06-07T03:12:31.989166Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['I', 'Learn', 'Python', 'Regex']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "l = re.split('-', 'I-Learn-Python-Regex')\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:48:53.762406Z",
     "start_time": "2018-06-07T05:48:53.753430Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['abcdefg', 'gmail', 'com']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "l = re.split('\\W', 'abcdefg@gmail.com')\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:47:38.918176Z",
     "start_time": "2018-06-07T05:47:38.913083Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['www', 'facebook', 'com']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "l = re.split('[.]', 'www.facebook.com')\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Step by Step creating RegEx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### STEP-1 : Create pattern object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:21:44.171122Z",
     "start_time": "2018-06-07T05:21:44.165136Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 're.Pattern'>\n"
     ]
    }
   ],
   "source": [
    "# compile() -> convert the pattern into regex object\n",
    "\n",
    "import re\n",
    "\n",
    "pattern = re.compile('Python')\n",
    "\n",
    "print(type(pattern))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### STEP-2 : Create Matcher object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:21:53.105420Z",
     "start_time": "2018-06-07T05:21:53.100434Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'callable_iterator'>\n"
     ]
    }
   ],
   "source": [
    "# finditer() -> we can check how many matcher are available\n",
    "\n",
    "matcher = pattern.finditer('I Python am learning python Regex in Python!')\n",
    "\n",
    "print(type(matcher))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### STEP-3 : Iterate over the Matcher"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:22:27.107742Z",
     "start_time": "2018-06-07T05:22:27.102753Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 're.Match'>\n",
      "Match is at:2, End:8, Pattern found: Python\n",
      "<class 're.Match'>\n",
      "Match is at:37, End:43, Pattern found: Python\n",
      "DONE!!\n"
     ]
    }
   ],
   "source": [
    "# start() -> starting index of matched string\n",
    "# end() -> end+1 index\n",
    "# group() -> returns matched sring\n",
    "\n",
    "for m in matcher:\n",
    "    print(type(m))\n",
    "    print('Match is at:{}, End:{}, Pattern found: {}'.\n",
    "          format(m.start(), m.end(), m.group()))\n",
    "print('DONE!!')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using Various Combinations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ab 0 2\n",
      "ab 3 5\n",
      "ab 5 7\n"
     ]
    }
   ],
   "source": [
    "# Pattern = 'ab'\n",
    "# Target = 'abaababa'\n",
    "# Way - 1\n",
    "\n",
    "import re\n",
    "\n",
    "pattern = re.compile('ab')\n",
    "\n",
    "matcher = pattern.finditer('abaababa')\n",
    "\n",
    "for m in matcher:\n",
    "    print(m.group(), m.start(), m.end())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ab 0 2\n",
      "ab 3 5\n",
      "ab 5 7\n"
     ]
    }
   ],
   "source": [
    "# Way - 2\n",
    "\n",
    "import re\n",
    "\n",
    "matcher = re.compile('ab').finditer('abaababa')\n",
    "\n",
    "for m in matcher:\n",
    "    print(m.group(), m.start(), m.end())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "aaaaa 0 5\n",
      "aaa 11 14\n",
      "aa 21 23\n",
      "a 30 31\n"
     ]
    }
   ],
   "source": [
    "# Way - 3\n",
    "# re.finditer(pattern, target)\n",
    "\n",
    "import re\n",
    "\n",
    "matcher = re.finditer('a+', 'aaaaabbcdegaaabdfgfdgaabjukilua')\n",
    "\n",
    "for m in matcher:\n",
    "    print(m.group(), m.start(), m.end())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:24:58.259291Z",
     "start_time": "2018-06-07T05:24:58.254301Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at:0, End:2, Pattern found: ab\n",
      "Match is at:3, End:5, Pattern found: ab\n",
      "Match is at:5, End:7, Pattern found: ab\n",
      "Total count:  3\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "matcher = re.finditer('ab', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at:{}, End:{}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:17:22.036827Z",
     "start_time": "2018-06-07T02:17:22.021800Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at:1, End:3, Pattern found: ba\n",
      "Match is at:4, End:6, Pattern found: ba\n",
      "Match is at:6, End:8, Pattern found: ba\n",
      "Total count:  3\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('ba', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at:{}, End:{}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'>\n",
      "<class 'int'>\n",
      "<class 'float'>\n",
      "<class 'str'>\n",
      "<class 'bool'>\n"
     ]
    }
   ],
   "source": [
    "lst = [1, 2.0, '3', True]\n",
    "\n",
    "print(type(lst))\n",
    "\n",
    "for i in lst:\n",
    "    print(type(i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'callable_iterator'>\n",
      "an 1 3\n",
      "<class 're.Match'>\n",
      "an 7 9\n",
      "<class 're.Match'>\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('an', 'Kanav Bansal')\n",
    "\n",
    "print(type(matcher))\n",
    "\n",
    "for m in matcher:\n",
    "    print(m.group(), m.start(), m.end())\n",
    "    print(type(m))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:18:37.371274Z",
     "start_time": "2018-06-07T02:18:37.361272Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 2, End: 3, Pattern found: b\n",
      "Total count:  2\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('[abc]', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:19:14.833187Z",
     "start_time": "2018-06-07T02:19:14.823192Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 2, End: 3, Pattern found: b\n",
      "Match is at: 5, End: 6, Pattern found: k\n",
      "Match is at: 7, End: 8, Pattern found: z\n",
      "Total count:  4\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('[a-z]', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:19:27.387351Z",
     "start_time": "2018-06-07T02:19:27.382352Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 1, End: 2, Pattern found: 7\n",
      "Match is at: 3, End: 4, Pattern found: @\n",
      "Match is at: 4, End: 5, Pattern found:  \n",
      "Match is at: 6, End: 7, Pattern found: 9\n",
      "Total count:  4\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('[^a-z]', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:22:23.415113Z",
     "start_time": "2018-06-07T02:22:23.405118Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 4, End: 5, Pattern found:  \n",
      "Total count:  1\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('\\s', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:22:30.758828Z",
     "start_time": "2018-06-07T02:22:30.753820Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 1, End: 2, Pattern found: 7\n",
      "Match is at: 2, End: 3, Pattern found: b\n",
      "Match is at: 5, End: 6, Pattern found: k\n",
      "Match is at: 6, End: 7, Pattern found: 9\n",
      "Match is at: 7, End: 8, Pattern found: z\n",
      "Total count:  6\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('\\w', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:22:37.868641Z",
     "start_time": "2018-06-07T02:22:37.858647Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 3, End: 4, Pattern found: @\n",
      "Match is at: 4, End: 5, Pattern found:  \n",
      "Total count:  2\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('\\W', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:23:00.635704Z",
     "start_time": "2018-06-07T02:23:00.630707Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Total count:  1\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('^a', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:30:25.898657Z",
     "start_time": "2018-06-07T05:30:25.893671Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 7, End: 8, Pattern found: z\n",
      "Total count:  1\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('z$', 'a7b@ k9z')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:24:41.182549Z",
     "start_time": "2018-06-07T02:24:41.177517Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 2, End: 3, Pattern found: a\n",
      "Match is at: 3, End: 4, Pattern found: a\n",
      "Match is at: 5, End: 6, Pattern found: a\n",
      "Match is at: 7, End: 8, Pattern found: a\n",
      "Total count:  5\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('a', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:26:12.250559Z",
     "start_time": "2018-06-07T02:26:12.245564Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 2, End: 4, Pattern found: aa\n",
      "Match is at: 5, End: 6, Pattern found: a\n",
      "Match is at: 7, End: 8, Pattern found: a\n",
      "Total count:  4\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('a+', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:26:16.696799Z",
     "start_time": "2018-06-07T02:26:16.686770Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 1, End: 1, Pattern found: \n",
      "Match is at: 2, End: 4, Pattern found: aa\n",
      "Match is at: 4, End: 4, Pattern found: \n",
      "Match is at: 5, End: 6, Pattern found: a\n",
      "Match is at: 6, End: 6, Pattern found: \n",
      "Match is at: 7, End: 8, Pattern found: a\n",
      "Match is at: 8, End: 8, Pattern found: \n",
      "Total count:  8\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('a*', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T02:26:39.569564Z",
     "start_time": "2018-06-07T02:26:39.559569Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 1, End: 1, Pattern found: \n",
      "Match is at: 2, End: 3, Pattern found: a\n",
      "Match is at: 3, End: 4, Pattern found: a\n",
      "Match is at: 4, End: 4, Pattern found: \n",
      "Match is at: 5, End: 6, Pattern found: a\n",
      "Match is at: 6, End: 6, Pattern found: \n",
      "Match is at: 7, End: 8, Pattern found: a\n",
      "Match is at: 8, End: 8, Pattern found: \n",
      "Total count:  9\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('a?', 'abaababa')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Match is at: 0, End: 1, Pattern found: a\n",
      "Match is at: 1, End: 1, Pattern found: \n",
      "Match is at: 2, End: 3, Pattern found: a\n",
      "Match is at: 3, End: 4, Pattern found: a\n",
      "Match is at: 4, End: 4, Pattern found: \n",
      "Match is at: 5, End: 5, Pattern found: \n",
      "Match is at: 6, End: 7, Pattern found: a\n",
      "Match is at: 7, End: 7, Pattern found: \n",
      "Match is at: 8, End: 9, Pattern found: a\n",
      "Match is at: 9, End: 9, Pattern found: \n",
      "Match is at: 10, End: 10, Pattern found: \n",
      "Match is at: 11, End: 11, Pattern found: \n",
      "Match is at: 12, End: 12, Pattern found: \n",
      "Total count:  13\n"
     ]
    }
   ],
   "source": [
    "matcher = re.finditer('a?', 'abaabbababbb')\n",
    "\n",
    "count = 0\n",
    "\n",
    "for m in matcher:\n",
    "    count += 1\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "print('Total count: ',count)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.match()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:38:08.010867Z",
     "start_time": "2018-06-07T05:37:51.582824Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter pattern: bcd\n",
      "<class 'NoneType'>\n",
      "Match is not available at beginning of the string!\n"
     ]
    }
   ],
   "source": [
    "# Used to match the given pattern at the beginning of the target string\n",
    "# If it finds the pattern than returns match object.\n",
    "# Now we can use start(), end(), group() with match object\n",
    "# If nothing found then retuns None.\n",
    "\n",
    "\n",
    "import re\n",
    "\n",
    "regex = input('Enter pattern: ')\n",
    "\n",
    "m = re.match(regex, 'abcdefgh')\n",
    "\n",
    "print(type(m))\n",
    "\n",
    "if m == None:\n",
    "    print('Match is not available at beginning of the string!')\n",
    "\n",
    "else:\n",
    "    print('Match found at beginning of the string.')\n",
    "    print('Match is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "    \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.search()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:40:19.936797Z",
     "start_time": "2018-06-07T05:40:08.915846Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter pattern: bcd\n",
      "Match available.\n",
      "First occurance is at: 1, End: 4, Pattern found: bcd\n"
     ]
    }
   ],
   "source": [
    "# search the target irrespective of the location\n",
    "# If match is found returns the first occurance\n",
    "# otherwie returns None.\n",
    "\n",
    "# If it finds the pattern than returns match object.\n",
    "# Now we can use start(), end(), group() with match object\n",
    "# If nothing found then retuns None.\n",
    "\n",
    "\n",
    "import re\n",
    "\n",
    "regex = input('Enter pattern: ')\n",
    "\n",
    "m = re.search(regex, 'abcdefghi')\n",
    "\n",
    "if m != None:\n",
    "    print('Match available.')\n",
    "    print('First occurance is at: {}, End: {}, Pattern found: {}'.format(m.start(), m.end(), m.group()))\n",
    "\n",
    "else:\n",
    "    print('Match is not available in the whole string!')\n",
    "    \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## re.match() vs re.search()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NO MATCH\n",
      "SEARCH SUCC\n"
     ]
    }
   ],
   "source": [
    "target = 'Dogs are better than cats'\n",
    "\n",
    "pattern = 'cats'\n",
    "\n",
    "m = re.match(pattern, target)\n",
    "\n",
    "if m == None:\n",
    "    print('NO MATCH')\n",
    "else:\n",
    "    print('MATCH SUCC')\n",
    "    \n",
    "m = re.search(pattern, target)\n",
    "\n",
    "if m == None:\n",
    "    print('NO SEARCH')\n",
    "else:\n",
    "    print('SEARCH SUCC')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Other Examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:49:56.456856Z",
     "start_time": "2018-06-07T05:49:56.445886Z"
    }
   },
   "outputs": [],
   "source": [
    "# # re.IGNORECASE flag\n",
    "\n",
    "# import re\n",
    "\n",
    "# s = 'I am learning Python'\n",
    "\n",
    "# m = re.search('python$', s)\n",
    "\n",
    "# if m:\n",
    "#     print('Cool!!')\n",
    "    \n",
    "# else:\n",
    "#     print('Not Cool!!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T05:53:01.499694Z",
     "start_time": "2018-06-07T05:52:53.528493Z"
    }
   },
   "outputs": [],
   "source": [
    "# # Python Identifier\n",
    "\n",
    "# import re\n",
    "\n",
    "# s = input('Enter any identifier to validate: ')\n",
    "\n",
    "# m = re.fullmatch('[a-zA-Z_]+[a-zA-Z0-9_]*', s)\n",
    "\n",
    "# if m:\n",
    "#     print(s, 'is valid')\n",
    "# else:\n",
    "#     print(s, 'not valid')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-06-07T03:34:11.063383Z",
     "start_time": "2018-06-07T03:34:08.899387Z"
    }
   },
   "outputs": [],
   "source": [
    "# # Match Phone number\n",
    "\n",
    "# import re\n",
    "\n",
    "# s = input('Enter a mobile number to validate: ')\n",
    "\n",
    "# m = re.fullmatch('[6-9]\\d{9}', s)\n",
    "\n",
    "# if m:\n",
    "#     print(s, 'is Valid')\n",
    "# else:\n",
    "#     print(s, 'not valid')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
